package com.zp.study.scloud.consumer.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class HttpUtils {


    /**
     * 发起POST请求 - form参数
     * 使用java原生方法
     * @param url 请求url
     * @param parms 参数集合
     * @param headers 请求头集合
     * @return
     */
    public static String sendPostRequest(String url, Map<String, String> parms, Map<String,String> headers){
        String ret = "";// 返回结果

        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        DataOutputStream dos = null;
        BufferedReader reader = null;
        String tempLine = null;
        String postParams = "";//构造的post请求参数

        try {
            URL localURL = new URL(url);
            URLConnection connection = localURL.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
            httpURLConnection.setDoOutput(true);     //需要输出
            httpURLConnection.setDoInput(true);      //需要输入
            httpURLConnection.setUseCaches(false);   //不允许缓存
            httpURLConnection.setRequestMethod("POST");// 设置请求方法为POST

            // 设置header
            if(headers != null){
                for(String key : headers.keySet()){
                    String value = headers.get(key);
                    httpURLConnection.setRequestProperty(key, value);
                }
            }

            // 设置参数
            if(parms != null){
                StringBuilder builder = new StringBuilder("");
                for(String key : parms.keySet()){
                    String valueStr = URLEncoder.encode(parms.get(key), "utf-8");// 对参数进行url转码
                    builder.append(key).append("=").append(valueStr).append("&");// 拼接参数 xxx=11&sss=12
                }
                postParams = builder.substring(0, builder.length() - 1);
            }

            dos=new DataOutputStream(httpURLConnection.getOutputStream());
            dos.writeBytes(postParams.toString());
            dos.flush();

            // 读取返回值
            inputStream = httpURLConnection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, "utf8"));
            StringBuilder resultBuilder = new StringBuilder();
            while ((tempLine = reader.readLine()) != null) {
                resultBuilder.append(tempLine);
            }
            ret = resultBuilder.toString();
        } catch (Exception e) {
            System.out.println("出现异常：" + e);
        } finally {
            try{
                if (reader != null)
                    reader.close();
                if (inputStreamReader != null)
                    inputStreamReader.close();
                if (inputStream != null)
                    inputStream.close();
                if(dos != null)
                    dos.close();
            }catch(Exception e){
                System.out.println("出现异常：" + e);
            }
        }
        return ret;
    }

    public static String doPost(String url,Map<String, String> parms, Map<String,String> headers){
        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
        String result = "";
        HttpPost httpPost = new HttpPost(url);

        // 拼接参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        for(String key : parms.keySet()){
            list.add(new BasicNameValuePair(key, parms.get(key)));
        }

        // 设置header
        for(String key : headers.keySet()){
            httpPost.setHeader(key, headers.get(key));
        }

        CloseableHttpResponse response = null;
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(list));
            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            System.out.println("========HttpResponseProxy：========" + statusCode);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
                System.out.println("========接口返回=======" + result);
            }
            EntityUtils.consume(entity);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
